<template>
  <div class="review_container">
    <div class="filter-container">
      <el-date-picker
        v-model="timeRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
        @change="handleTimeChange"
      />
    </div>

    <el-table :data="tables">
      <el-table-column prop="username" label="姓名" />
      <el-table-column prop="score" label="分数" />
      <el-table-column prop="usedTime" label="用时" />
      <el-table-column prop="createTime" label="创建时间">
        <template #default="scope">
          {{ scope.row.createTime?.replace("T", " ") }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            text
            type="primary"
            @click="handleDetail(scope.row.selfTestId)"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :page-count="count"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import selfTestResult from "@/api/selfTest/selfTestResult";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();
const currentPage = ref(1);
const tables = ref([]);
const count = ref(0);
let pageSize = 10;

// 添加时间范围响应式变量
const timeRange = ref([]);
const startTime = ref("");
const endTime = ref("");

const handleDetail = (selfTestId) => {
  router.push({
    path: "/learning/learn",
    query: { selfTestId, type: "回顾错题" },
  });
};

const handleCurrentChange = async (page) => {
  currentPage.value = page;
  await getList();
};

const handleTimeChange = (val) => {
  if (val) {
    startTime.value = val[0];
    endTime.value = val[1];
  } else {
    startTime.value = "";
    endTime.value = "";
  }
  // 重新加载数据
  getList();
};

const getList = async () => {
  try {
    const res = await selfTestResult.getList(
      route.query.selectedId,
      currentPage.value,
      pageSize,
      startTime.value,
      endTime.value
    );
    tables.value = res.data;
    console.log(tables.value);

    // 获取总数
    const totalRes = await selfTestResult.getTotal(
      route.query.selectedId,
      startTime.value,
      endTime.value
    );
    count.value = Math.ceil(totalRes.data / pageSize);
    console.log(count.value);
  } catch (error) {
    console.error("Error fetching data:", error);
    ElMessage.error("获取数据失败");
  }
};

onMounted(async () => {
  await getList();
});
</script>

<style scoped>
.review_container {
  background-color: #f0f2f5;
}

.filter-container {
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>
